package com.ayf.payment.game.api.controller.eqb;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.eqb.constant.ConfigConstant;
import com.ayf.payment.game.api.eqb.service.EQBService;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @Description: E签宝
 * @Author: zh-liang
 * @Date : 2020-06-15 21:20
 */
@RestController
public class EQBController {

    @Autowired
    private EQBService eqbService;

    @RequestMapping("/eqb/async")
    public void async(HttpServletRequest request) {
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            SafeVerify sv = new SafeVerify();
            Map<String, Object> map = sv.checkPass(uniqueId, request, ConfigConstant.PROJECT_SECRET);
            String signStatus = map.get("signStatus") + "";
            if ("true".equals(signStatus)) {
                String data = map.get("body") + "";
                JSONObject jsonData = JSON.parseObject(data);
                String accountId = jsonData.getString("accountId");
                if ("eb94e9413a8b4bb7a0cad24be03102eb".equals(accountId) || "483da4f5cf604d45916ccc1134e7a466".equals(accountId)) {
                    LogPortal.info("[{}]E签宝-平台自动签署-异步通知成功,accId[{}]", uniqueId, accountId);
                    return;
                }
                Integer signResult = jsonData.getInteger("signResult");
                String flowId = jsonData.getString("flowId");
                Date signTime = jsonData.getDate("signTime");
                String flowStatus = jsonData.getString("flowStatus");
                if (signResult == null && StrUtil.isNotBlank(flowStatus) && "7".equals(flowStatus)) {
                    signResult = 4;
                }
                if (signResult == null) {
                    LogPortal.info("[{}]E签宝-异步通知结束（非用户手动签署）,accId[{}]，参数：{}", uniqueId, accountId, jsonData.toJSONString());
                    return;
                }
                eqbService.asyncHandle(uniqueId, accountId, flowId, signResult, signTime);
                LogPortal.info("[{}]E签宝-用户手动签署-异步通知成功,accId[{}]", uniqueId, accountId);
            } else {
                LogPortal.error("[{}]E签宝-协议签署结果-异步通知验签失败", uniqueId);
            }
        } catch (Exception e) {
            LogPortal.error("[{}]E签宝-协议签署结果-异步通知失败,发生[{}],异常信息为[{}]", e, uniqueId, e.getClass().getSimpleName(),
                    e.getMessage());
        }
    }

    @RequestMapping("/eqb/ok")
    public String ok() {
        return "ok";
    }
}
